import store from '@/store';

// 小程序更新
export function updataManager() {
	const updateManager = uni.getUpdateManager();
	updateManager.onCheckForUpdate(function(res) {
		// 请求完新版本信息的回调
		console.log("是否有新版本======"+res.hasUpdate);
		if (res.hasUpdate) {
			updateManager.onUpdateReady(function(res) {
				uni.showModal({
					title: '更新提示',
					content: '新版本已经准备好，是否重启应用？',
					success(res) {
						if (res.confirm) {
							// 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
							updateManager.applyUpdate();
						}
					}
				});
			});	
			updateManager.onUpdateFailed(function (res) {
			  // 新的版本下载失败
			  uni.showModal({
			  	title: '更新提示',
			  	content: '请检查网络设置，下载失败',
			  	showCancel: false
			  });
			});
		}
	});
}
// 参数解码
export function getQueryObject(url) {
	url = url == null ? window.location.href : url
	const search = url.substring(url.lastIndexOf('?') + 1)
	const obj = {}
	const reg = /([^?&=]+)=([^?&=]*)/g
	search.replace(reg, (rs, $1, $2) => {
		const name = decodeURIComponent($1)
		let val = decodeURIComponent($2)
		val = String(val)
		obj[name] = val
		return rs
	})
	return obj
}
// 复制
export function copyStr(str) {
	uni.setClipboardData({
		data: str,
		success: function() {
			console.log('success');
		}
	});
}
// 拨打电话
export function phoneFn(tel) {
	console.log(tel)
	uni.makePhoneCall({
		phoneNumber: tel ? tel : '114' //仅为示例
	});
}

// 查看地址
export function viewMapFn(obj) {
	uni.openLocation({
		name: obj.name,
		address: obj.address,
		latitude: parseFloat(obj.lat),
		longitude: parseFloat(obj.long),
		success: () => {
			console.log('success');
		},
		fail: (err) => {
			console.log(err)
		}
	});
}

export function payFn(res) {
	let money = res.data.total_money
	let oil = res.data.send_oil
	uni.requestPayment({
		provider: 'wxpay',
		timeStamp: res.data.timeStamp + '',
		nonceStr: res.data.nonceStr,
		package: res.data.package,
		signType: "MD5",
		paySign: res.data.sign,
		success: (res) => {
			uni.redirectTo({
				url: `/pagesB/PayResult/PayResult?orderMoney=${money}&orderOil=${oil}`,
			})
		},
		fail: (err) => {
			console.log('fail:' + JSON.stringify(err));
		}
	});
}
export function sLogin() {
	uni.login({
		provider: "weixin", //wx
		success: (loginRes) => {
			let storageObj = uni.getStorageSync("lifeData")
			let obj = {
				code: loginRes.code,
				union_id: storageObj.vuex_business.union_id,
				union_join_id: storageObj.vuex_business.union_join_id,
			}
			uni.$u.api.loginApi(obj).then(res => {
				console.log('---login---', res)
				uni.$u.vuex("vuex_token", res.data.token);
				uni.$u.vuex("vuex_session_key", res.data.session_key);
				uni.$u.vuex("vuex_isLogin", true);
				uni.$u.vuex("vuex_isRegister", true);
				uni.$u.vuex("vuex_business.union_id", res.data.union_id)
				uni.$u.vuex("vuex_business.union_join_id", res.data.union_join_id)
			})
		}
	});
}

function loginFn(proStr) {
	uni.getUserProfile({
		desc: '用于完善会员资料',
		success: (resUserInfo) => {
			uni.login({
				provider: proStr, //wx
				success: (loginRes) => {
					// console.log(uni.getStorageSync('lifeData'))
					let storageObj = uni.getStorageSync("lifeData")
					console.log(storageObj)
					let obj = {
						code: loginRes.code,
						name: resUserInfo.userInfo.nickName,
						headimgurl: resUserInfo.userInfo.avatarUrl,
						union_id: storageObj.vuex_business.union_id,
						union_join_id: storageObj.vuex_business.union_join_id,
					}
					// let obj = {
					// 			code: loginRes.code,
					// 			nickname: infoRes.userInfo.nickName,
					// 			headimgurl: infoRes.userInfo.avatarUrl,
					// 			city: infoRes.userInfo.city,
					// 			gender: infoRes.userInfo.gender,
					// 			encryptedData: infoRes.encryptedData,
					// 			iv: infoRes.iv,
					// 			pid: store.state.sharerUserId
					// 		}
					uni.$u.api.loginApi(obj).then(res => {
						console.log('---login---', res)
						uni.$u.vuex("vuex_user.avatarUrl", res.data.headimgurl);
						uni.$u.vuex("vuex_user.nickName", res.data.name);
						uni.$u.vuex("vuex_user.mobile", res.data.mobile);
						uni.$u.vuex("vuex_user.userId", res.data.id);
						uni.$u.vuex("vuex_token", res.data.token);
						uni.$u.vuex("vuex_session_key", res.data.session_key);
						uni.$u.vuex("vuex_isLogin", true);
						uni.$u.vuex("vuex_isRegister", true);
						uni.$u.vuex("vuex_business.union_id", res.data.union_id)
						uni.$u.vuex("vuex_business.union_join_id", res.data
							.union_join_id)
					})
				}
			});
		}
	})

}
export function login() {
	console.log("login")
	uni.getProvider({
		service: 'oauth',
		success: function(res) {
			if (~res.provider.indexOf('weixin')) {
				loginFn('weixin')
			} else if (~res.provider.indexOf('toutiao')) {
				loginFn('toutiao')
			}
		}
	});
}

export function checkLogin() {
	uni.$u.vuex("vuex_token", "");
	uni.$u.vuex("vuex_status", 0);
	// uni.$u.vuex("vuex_user",{
	// 		avatarUrl: require("@/static/logo.png"),
	// 		nickName: "欢迎来到神灯圈子",
	// 	});
	uni.$u.vuex("vuex_isLogin", false);
}

/**
 * 拼接对象为请求字符串
 * 对于需要编码的文本（比如说中文）我们要进行编码
 * @param {Object} obj - 待拼接的对象
 * @returns {string} - 拼接成的请求字符串
 **/

export function formatGetUri(obj) {
	const params = [];
	Object.keys(obj).forEach(key => {
		let value = obj[key];

		if (typeof value !== 'undefined' || value !== null) {
			params.push([key, encodeURIComponent(value)].join('='));
		}
	});
	return '?' + params.join('&');
}
